﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MeTalker.Aide;

namespace MeTalker.Aide.Forms
{
    internal delegate void FormCloseHandler(object sender, TalkerState state);
    internal delegate void MessageCallback(object sender,string msg);
    internal enum TalkerState
    {
        Deafult = 0,
        AutoReply = 1,
        Hidden = 2,
        Display = 3,
        Closed = 4,
        ShoppingGuide = 5,
        AutoReceiv = 6,
        AVAILABLE = 7,
        AutoQueryPieces = 8,//自动查件
        AutoMenuGuide = 9,//菜单导购
        AutoChatAid = 10,//辅助聊天
        NoLicense = 11
       // All = 11
    }

    internal class TalkerBase : Form
    {
        TalkerState _workMode;
        public TalkerState WorkMode { get { return _workMode; } }
        private WebBrowser webBrowser;
        private System.Threading.Timer mTimer;
        string oldHtml;
        object obj = new object();
        MessageCallback messageCallback;
        internal MessageCallback OrderCallback { get; set; }
        internal ProcInfo Proc { get; private set; }
        #region 属性
        internal TalkerState CustoemrState { get;set; }
        int _screemWidth;
        int _screemHeight;
        internal BodyMessageHandler BodyMessage;
        private string user;
        internal string SelectUser
        {
            get
            {
                return user;
            }
        }
        internal BodyHandler MessageBodyHandler { get; set; }
        internal TalkerHelper helper;
        internal IntPtr mainHandler;
       // internal string Account { get; private set; }
        protected int ScreemWidth
        {
            get
            {
                return _screemWidth;
            }
        }

        protected int ScreemHeight
        {
            get { return _screemHeight; }
        }
        protected string BaseDirectory
        {
            get;
            private set;
        }
        internal TalkerState State { get;  set; }
        //internal FormCloseHandler FormCloseHandlerCallBack
        //{
        //    get;
        //    private set;
        //}
        
        private IDictionary<string, MessageBody> caches = new Dictionary<string, MessageBody>();
        private IDictionary<string, MessageBody> autocaches = new Dictionary<string, MessageBody>();

        internal IDictionary<string, MessageBody> AutoCaches
        {
            get
            {
                return autocaches;
            }
        }
        internal IDictionary<string, MessageBody> Caches
        {
            get
            {
                return caches;
            }
        }
        #endregion

        #region 构造
        internal TalkerBase()
            : base()
        {
        }

        internal TalkerBase(ProcInfo proc)
        {
            _workMode = TalkerState.AutoChatAid;
            Proc = proc;
            messageCallback = new MessageCallback(MessageCallback);

            CustoemrState = TalkerState.Deafult;
            BodyMessage = new BodyMessageHandler(BodyMessageHandler);
            webBrowser = new WebBrowser();
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            //Account = account;
           // FormCloseHandlerCallBack = callBack;
            this.FormClosing += new FormClosingEventHandler(FormBase_FormClosing);
            BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            _screemWidth = System.Windows.Forms.SystemInformation.WorkingArea.Width;    //屏幕宽度
            _screemHeight = System.Windows.Forms.SystemInformation.WorkingArea.Height;   //屏幕高度（不包括系统任务栏）
            helper = new TalkerHelper(proc);
            helper.Init(out mainHandler);
            this.Load += new EventHandler(FormBase_Load);
            user = helper.HandlerSelectUserMessage();
            //Console.WriteLine(user);
        }


        void FormBase_Load(object sender, EventArgs e)
        {
            
        }

        protected void StartTime(int dueTime) {
            mTimer = new System.Threading.Timer(TimeCallBack, null, dueTime, 50);
        }

        protected void StopTime()
        {
            if (mTimer != null)
                mTimer.Dispose();
            mTimer = null;
        }
        #endregion

       

        void MessageCallback(object sender, string msg) {
            try
            {
                if (OrderCallback != null)
                    OrderCallback.BeginInvoke(this, msg, null, null);
            }
            catch { }
        }

        bool isFrist = true;
        void BodyMessageHandler(object sender, string msg, string user)
        {
            try
            {
                MessageBody msgBody = UtilHelper.FormatRequestMessage(msg, this.Proc.Alias);
                if (msgBody != null)
                {
                    if (MessageBodyHandler != null)
                        MessageBodyHandler.BeginInvoke(this, msgBody, null, null);
                    if (isFrist)
                    {
                        if (!msgBody.SendName.Equals(this.Proc.Alias))
                            user = msgBody.SendName;
                        isFrist = false;
                    }
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("BodyMessageHandler", ex);
            }
        }

        #region 事件处理

        void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                HtmlElement content = webBrowser.Document.GetElementById("content");
                HtmlDocument contentDoc = content.Document;
                for (int i = 0; i < content.All.Count; i++)//取出查看DIV标签
                {
                    if (contentDoc.All[i].TagName.ToUpper().Equals("DIV"))
                    {
                        if (contentDoc.All[i].Id == "MsgElement")
                        {
                            HandleContent(contentDoc.All[i]);
                        }
                    }
                }
            }
            catch { }
        }

        void HandleContent(HtmlElement docElement)
        {
            try
            {
                string sendName = string.Empty;
                string sendId = string.Empty;
                string msgId = string.Empty;
                string msgTime = string.Empty;
                string senderSite = string.Empty;
                string content = string.Empty;
                for (int i = 0; i < docElement.All.Count; i++)//取出查看DIV标签
                {
                    if (docElement.All[i].TagName.ToUpper().Equals("SPAN"))
                    {
                        if (docElement.All[i].Id == "SenderName")
                        {
                            sendName = docElement.All[i].InnerText;
                        }
                        else if (docElement.All[i].Id == "MsgTime")
                        {
                            msgTime = docElement.All[i].InnerText;
                            if (!string.IsNullOrEmpty(msgTime) && msgTime.Length > 19)
                            {
                                msgTime = msgTime.Substring(1, 19);
                            }
                        }
                        else if (docElement.All[i].Id == "SenderSite")
                        {
                            senderSite = docElement.All[i].InnerText;
                        }
                    }

                    if (docElement.All[i].TagName.ToUpper().Equals("DIV"))
                    {
                        if (docElement.All[i].Id == "MsgContent")
                        {
                            sendId = docElement.All[i].Children[0].GetAttribute("SendID");
                            msgId = docElement.All[i].Children[0].GetAttribute("msgId");
                            string id = docElement.All[i].Children[0].GetAttribute("id");
                            content = HandlerImgContent(docElement.All[i].Children[0], id);
                        }
                    }
                }

                if (caches != null && !caches.ContainsKey(msgTime))
                {
                    MessageBody msgbody = new MessageBody();
                    msgbody.Content = content;
                    msgbody.SenderSite = senderSite;
                    msgbody.SendId = sendId;
                    msgbody.SendName = sendName;
                    msgbody.MsgId = msgId;
                    msgbody.MsgTime = msgTime;
                    caches.Add(msgTime, msgbody);
                    if (!Proc.Alias.Equals(sendName))
                    {
                        user = sendName;
                    }
                    if (MessageBodyHandler != null)
                        MessageBodyHandler.BeginInvoke(this, msgbody, null, null);
                    //Console.WriteLine("当前数" + caches.Count);
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("HandleContent", ex);
            }
        }

        string HandlerImgContent(HtmlElement docElement, string id)
        {
            try
            {
                string msgs = string.Empty;
                for (int i = 0; i < docElement.All.Count; i++)//取出查看DIV标签
                {
                    if (docElement.All[i].TagName.ToUpper().Equals("IMG"))
                    {
                        string alt = docElement.All[i].GetAttribute("alt");
                        if (!string.IsNullOrEmpty(alt))
                        {
                            msgs += alt.Split(' ')[0];
                        }
                    }

                    if (docElement.All[i].TagName.ToUpper().Equals("FONT"))
                    {
                        msgs += docElement.All[i].InnerText;
                    }
                }
                return msgs;
            }
            catch { return ""; }
        }
        
        #endregion

        internal string SEND_MSG { get; private set; }
        internal string SET_MSG { get; private set; }
        internal string OLD_MSG { get; private set; }
        internal string DISPLAY_MSG { get; private set; }

        #region 发送

        internal string GetReplyMessage()
        {
            if (helper != null)
                return helper.GetEditMessage();
            return string.Empty;
        }

        bool lock_msg = false;
        internal void SetForegroundMainWindow()
        {
            if (helper != null)
                helper.SetForegroundMainWindow(helper.HandleWinForm);
        }
        //internal void SendMText(string msg)
        //{
        //    if (helper != null)
        //        SendText(msg);
        //}
        internal void SendText(string msg)
        {
            SendText(helper.HandleMessageBody, msg);
        }

        internal void SendText(IntPtr intptr, string msg)
        {
            lock_msg = true;
            if (helper != null)
            {
                SEND_MSG = msg.Trim();
                helper.SendText(intptr, SEND_MSG);
            }
            lock_msg = false;
        }

        internal void SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam)
        {
            lock_msg = true;
            helper.SendMessage(hwnd, wMsg, wParam, lParam);
            lock_msg = false;
        }

        internal void SetText(string msg)
        {
            SetText(helper.HandleMessageBody, msg);
        }

        internal void SetText(IntPtr intptr, string msg)
        {
            lock_msg = true;
            if (helper != null)
            {
                SET_MSG = msg.Trim();
                helper.SetText(intptr, SET_MSG);
            }
            lock_msg = false;
        }
        #endregion

        protected virtual void TimeCallBack(object sender)
        {
            try
            {
                if (helper != null)
                {
                   string temoUser= helper.HandlerSelectUserMessage();
                       user = temoUser;
                    
                    string text = helper.GetEditMessage();
                    OLD_MSG = text;
                   
                    if (text != null)
                    {
                        if(!lock_msg)
                                messageCallback.BeginInvoke(this, text, null, null);
                               
                    }
                    lock (obj)
                    {
                        string dispText = helper.GetMessageText();
                        if (!string.IsNullOrEmpty(dispText) && !dispText.Equals(DISPLAY_MSG))
                        {
                            
                            DISPLAY_MSG = dispText;
                            BodyMessage.BeginInvoke(this, dispText, user, null, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("TimeCallBack", ex);
            }
        }

        void FormBase_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                State = TalkerState.Closed;
                StopTime();
            }
            catch
            {
            }
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(234)))), ((int)(((byte)(247)))), ((int)(((byte)(254)))));
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Name = "FormBase";
            this.ResumeLayout(false);
        }
    }
}